package com.buobao.oa.controller;

import com.alibaba.fastjson.JSON;
import com.buobao.oa.entity.Notice;
import com.buobao.oa.entity.User;
import com.buobao.oa.service.NoticeService;
import com.github.pagehelper.Page;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "NoticeServlet", urlPatterns = "/notice/*")
public class NoticeServlet extends HttpServlet {
    private NoticeService noticeService = new NoticeService();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri = req.getRequestURI();
        String path = uri.substring(uri.lastIndexOf("/")+1);
        if ("list".equals(path)) {
            list(req, resp);
        }
    }

    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        User user = (User)req.getSession().getAttribute("login_user");
        int page = Integer.parseInt(req.getParameter("page"));
        int limit = Integer.parseInt(req.getParameter("limit"));
        Page<Notice> listPage = noticeService.selectByEmployId(user.getEmployeeId(),page,limit);
        Map result = new HashMap<>();
        result.put("code", "0");
        result.put("msg", "success");
        result.put("count",listPage.getTotal());
        result.put("data", listPage.getResult());
        String json = JSON.toJSONString(result);
        resp.setContentType("text/html;charset=utf-8");
        resp.getWriter().println(json);
    }
}
